import { Request, Response, NextFunction } from 'express';
import { get, request } from 'http';
import { getConfig } from '../config';

let config = getConfig();
export class ProxyMiddleware {
    constructor() { }

    static rootPath = '/proxy/';
    
    async use(req: Request, res: Response, next: NextFunction) {
        const { url, headers, method, body } = req;

        let targetUrl = url.replace(ProxyMiddleware.rootPath, '/');
        targetUrl = config.plmUrl + targetUrl;
        console.log('targetUrl', targetUrl);
        
        const options = {
            url: targetUrl,
            headers: headers,
            method: method,
            body: body
        };

        // url = url.replace(ProxyMiddleware.rootPath, '');


        const proxyReq = request(options, (proxyRes) => {
            res.writeHead(proxyRes.statusCode, proxyRes.headers);
            proxyRes.pipe(res);
        });

        req.pipe(proxyReq);

    }
}